package com.changgou.oauth.controller;

import com.changgou.entity.Result;
import com.changgou.entity.ResultCode;
import com.changgou.entity.StatusCode;
import com.changgou.oauth.exception.MyBaseException;
import com.changgou.oauth.service.AuthService;
import com.changgou.oauth.util.AuthToken;
import com.changgou.oauth.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * @description:
 * @author: 大佬味的小男孩
 * @date: 2020-07-30 14:45
 **/
@Controller
@RequestMapping("auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Value("${auth.clientId}")
    private String clientId;

    @Value("${auth.clientSecret}")
    private String clientSecret;

    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;

    /**
     * @param
     * @return java.lang.String
     * @description: 跳转登录页面
     * @author 大佬味的小男孩
     * @date 2020/07/30 23:26
    */
    @RequestMapping("tologin")
    public String tologin(@RequestParam(value = "FROM",required = false,defaultValue = "") String from, Model model) {
            model.addAttribute("from",from);
        return "login";
    }

    /**
     * @param username
     * @param password
     * @param response
     * @return com.changgou.entity.Result
     * @description: 用户登录 生成令牌
     * @author 大佬味的小男孩
     * @date 2020/07/30 23:23
     */
    @PostMapping("login")
    @ResponseBody
    public Result login(String username, String password, HttpServletResponse response) {

        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            MyBaseException.throwe(ResultCode.IS_EMPTY);
        }

        //生成令牌
        AuthToken authToken = authService.login(username, password, clientId, clientSecret);

        // 将jti作为Cooke
        this.saveJtiToCookie(authToken.getJti(), response);
        return new Result(true, StatusCode.OK, "登录成功", authToken.getJti());

    }

    private void saveJtiToCookie(String jti, HttpServletResponse response) {
        //利用工具类生成cookie
        System.out.println(cookieDomain + ":" + cookieMaxAge);
        CookieUtil.addCookie(response, cookieDomain, "/", "uid", jti, cookieMaxAge, false);

    }
}
